"""
自定义的分页组件。若使用，需要做以下几件事：

在视图函数中：
    def pretty_list(request):
        # 1、根据情况筛选需要的数据queryset
        queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
        # 实例化分页对象
        page_obj = Pagination(request,queryset,page_param="page",page_size=8,plus=5)
        # 分页后返回的数据
        context = {
            "items": page_obj.items,             # 分完页后的数据
            "page_string": page_obj.html()       # 生成页码
        }
        return render(request,'pretty_list.html',context)

在HTML中：
    # 分页后显示的数据（不需要书写）
    {% for item in items %}
        <tr>
            <td align="center">{{item.id}}</td>
            <td align="center">{{item.xxxx}}</td>
            。。。。。。
        </tr>
    {% endfor %}

    # 分页显示
    <ul  class="pagination">
        {{page_string}}
    </ul>
"""
import copy
from django.utils.safestring import mark_safe


class Pagination(object):
    def __init__(self,request,queryset,page_param="page",page_size=8,plus=5):
        """
        :params  request：请求的对象
        :params  queryset：符合条件的数据（根据这个数据进行分页处理）
        :params  page_param：在url中传递的获取分页的参数，例如：/pretty/list/?page=12
        :params  page_size：每页显示多少条数据
        :params  plus：显示当前页的前后几页（页码）
        """
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict
        self.page_param = page_param
        page = request.GET.get(self.page_param, '1')
        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        self.page = page
        self.page_size = page_size
        self.start = (page - 1) * page_size
        self.end = page * page_size
        self.queryset = queryset[self.start:self.end]
        data_counts = queryset.count()
        page_counts, div = divmod(data_counts, page_size)
        if div:
            page_counts += 1
        self.page_counts = page_counts
        self.plus = plus

    def html(self):
        # 页码数较少时，显示1到最大页码
        if self.page_counts <= 2 * self.plus + 1:
            start_page = 1
            end_page = self.page_counts
        else:
            # 页码数较多时，前面页面不能小于0
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus + 1
            else:
                # 页码数较多时，后面页码不能大于最大页码
                if (self.page + self.plus) > self.page_counts:
                    start_page = self.page_counts - 2 * self.plus
                    end_page = self.page_counts
                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus

        # 在浏览器上显示页码
        page_str_list = []
        self.query_dict.setlist(self.page_param, [1])
        page_str_list.append(f"<li><a href='?{self.query_dict.urlencode()}'>首页</a></li>")
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            page_pre = f"<li><a href='?{self.query_dict.urlencode()}'>上一页</a></li>"
            page_str_list.append(page_pre)
        for i in range(start_page, end_page + 1):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = f"<li class='active'><a href='?{self.query_dict.urlencode()}'>{i}</a></li>"
            else:
                ele = f"<li><a href='?{self.query_dict.urlencode()}'>{i}</a></li>"
            page_str_list.append(ele)
        if self.page < self.page_counts:
            self.query_dict.setlist(self.page_param, [self.page+1])
            page_after = f"<li><a href='?{self.query_dict.urlencode()}'>下一页</a></li>"
            page_str_list.append(page_after)
        self.query_dict.setlist(self.page_param, [self.page_counts])
        page_str_list.append(f"<li><a href='?{self.query_dict.urlencode()}'>尾页</a></li>")
        to_page = """
            <li>
                <form method="get" style="float:left">
                    <input class="form-cotrol" type="text" name="page" style="width:80px;height:34px;float:left;display:inline-block;border-dadius:0" placeholder="输入页码">
                    <button class="btn btn-default" style="border-radius:0" type="submit">跳转</button>
                </form>
            </li>
        """
        page_str_list.append(to_page)
        page_string = mark_safe("".join(page_str_list))  # html格式在浏览器上转为显示内容
        return page_string